package com.hu.demo1.controller;

import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.hu.demo1.commen.R;
import com.hu.demo1.utils.AliyunSMS;
import com.hu.demo1.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(value = "*")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/sendSMS")
    public R<String> sendSMS(String phone){
        // 检查手机号是否符合规范
        if (phone == null || phone.isBlank()){
            return R.error("手机号不符合规范1");
        }else if (phone.matches("^1[3456789]\\d{9}$")){
            // 发送短信
            String code = StringUtil.getRandomString(4);
            try{
                SendSmsResponseBody sendSmsResponseBody = AliyunSMS.sendSMS(phone,code);
                if("OK".equals(sendSmsResponseBody.getCode())){
                    //将验证码放入redis
                    redisTemplate.opsForValue().set("code_"+phone,code,10, TimeUnit.MINUTES);
                    return R.success("发送成功");
                }else {
                    return R.error("发送失败");
                }
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


        }else {
            return R.error("手机号不符合规范");
        }
    }
}
